About 4380 letters

About 22 minutes

#Python's file reading and writing

File I/O is one of the most basic operations. Python uses the built-in function open to open files, then the read method to read files, the write method to write to files, and finally the close method to close the files.

f = open('./1.txt', 'w') # 'w' means open file in write-only mode f.write('Test') f.close() f = open('./1.txt', 'r') # 'r' means open file in read-only mode text = f.read() print(text) f.close()

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#File Opening Modes

  • r: Read mode; throws error if file does not exist.
  • w: Write mode; clears existing file if it exists.
  • a: Append mode; offset starts at file end.
  • +: Read and write mode.
  • b: Binary mode, typically used for non-text files like images or executables.
ModeDescriptionFile ExistsFile Not ExistInitial OffsetReturn Type
rRead-onlyOpens fileRaises FileNotFoundErrorFile startstr
wWrite-onlyClears fileCreates new fileFile startstr
aAppend writeOpens fileCreates new fileFile endstr
r+Read and writeOpens fileRaises FileNotFoundErrorFile startstr
w+Read and writeClears fileCreates new fileFile startstr
a+Append read and writeOpens fileCreates new fileFile endstr
rbRead-only (binary)Opens fileRaises FileNotFoundErrorFile startbytes
wbWrite-only (binary)Clears fileCreates new fileFile startbytes
abAppend write (binary)Opens fileCreates new fileFile endbytes
rb+Read/write (binary)Opens fileRaises FileNotFoundErrorFile startbytes
wb+Read/write (binary)Clears fileCreates new fileFile startbytes
ab+Append read/write(binary)Opens fileCreates new fileFile endbytes

#File Offset

The file offset marks the current position for reading or writing in the file. In Python, use the tell() method to get the offset and seek() to set the offset. Reading or writing automatically advances the offset.

  • For text files, the offset unit is characters.
  • For binary files (opened with b mode), the offset unit is bytes.
import io f = open('./1.txt', 'w') print('Offset when opening file:', f.tell()) # Check offset f.write('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # Write content print('Offset after writing:', f.tell()) # Check offset f.close() f = open('./1.txt', 'rb') print('Offset when opening file:', f.tell()) f.seek(10, io.SEEK_SET) # Offset = file start + 10 bytes print('Current offset:', f.tell()) f.seek(-9, io.SEEK_END) # Offset = file end - 9 bytes print('Current offset:', f.tell()) f.seek(-5, io.SEEK_CUR) # Offset = current position - 5 bytes print('Current offset:', f.tell())

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Writing in the middle of a file overwrites existing content, it does not insert:

import io f = open('./1.txt', 'w') f.write('ABCDEFGHIJKLMNOPQRSTUVWXYZ') f.seek(10, io.SEEK_SET) f.write('XXXXXXXX') # Overwrites at offset 10 f.close() f = open('./1.txt', 'r') print(f.read())

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Using with

Manually closing files every time can be tedious and if an error occurs, the file might not be closed properly. In Python, with statement solves this:

with open('/path/to/file', 'r') as f: pass

When the with block ends, f.__exit__() is automatically called to close the file, regardless of normal or exceptional exit.

Any object with __enter__ and __exit__ methods can be used with with. Upon entering with, __enter__ is called automatically; upon leaving, __exit__ is called.

Example:

class Refrigerator: def __enter__(self): print('Opening refrigerator') def __exit__(self, type, value, traceback): print('Closing refrigerator') refrigerator = Refrigerator() with refrigerator: pass

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Created in 5/15/2025

Updated in 5/21/2025